package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func reverseKGroup(head *ListNode, k int) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}
	dummy := &ListNode{}
	current := dummy
	current.Next = head
	//current = current.Next
	var listAddresses []*ListNode
	for current.Next != nil {
		current2 := current

		//获取前K个链表
		for i := 0; i < k; i++ {
			if current2.Next == nil {
				return dummy.Next
			}
			listAddresses = append(listAddresses, current2.Next)
			//if current2.Next == nil && i != k-1 {
			//	return dummy.Next
			//}
			current2 = current2.Next
		}
		listAddresses = append(listAddresses, current2.Next)
		//调换前k个
		for i := 0; i < k; i++ {
			current.Next = listAddresses[k-i-1]
			current = current.Next
		}
		current.Next = listAddresses[k]
		//current = current.Next
		listAddresses = nil

	}
	return dummy.Next

}

func printList2(head *ListNode) {
	for head != nil {
		fmt.Print(head.Val, " ")
		head = head.Next
	}
	fmt.Println()
}

func main() {

	l1 := &ListNode{Val: 1, Next: &ListNode{Val: 2, Next: &ListNode{Val: 3, Next: &ListNode{Val: 4, Next: &ListNode{Val: 5}}}}}
	l2 := &ListNode{Val: 1, Next: &ListNode{Val: 2, Next: &ListNode{Val: 3, Next: &ListNode{Val: 4, Next: &ListNode{Val: 5}}}}}

	printList2(reverseKGroup(l1, 2))
	printList2(reverseKGroup(l2, 3))

}
